console.log('进入到api.js')
let http = require('http')
var db = require('.././mysql/index.js')
function getApi (req,res,url){
    let params = url.query;//get请求的参数获取
    if(/form/.test(url.pathname)){
        if(req.method=='GET'){
            res.writeHead(200, {
                "Content-Type": "text/html;charset=UTF-8"
                });
            res.end(`您的用户名为：${params.username}`);
        }else{
            req.on('data', function (chunk) {
                params += chunk;
            });
          
            req.on('end', function () {
              res.writeHead(200, {"Content-Type": "text/plain;charset=UTF-8"});
              res.write("您的用户名为: " + params);

              res.end();
            });
        }
    }else if(/weather/.test(url.pathname)){//node请求第三方api
        http.get("http://www.tianqiapi.com/api/?city="+ encodeURI(url.query.city),function(response) {
            var body = '';
            response.on('data', function(d) {
                body += d;
            });
            response.on('end', function() {
                var parsed = JSON.parse(body);
                res.writeHead(200, {
                    "Content-Type": "application/json;charset=UTF-8"
                    });
                res.end(JSON.stringify(parsed));
            });
        })
    }else if(/add/.test(url.pathname)){//增
        let addSQL = `INSERT INTO log ( create_time,user_href,user_ip,user_device)
        VALUES
        ( NOW() , '${params.user_href}', '${params.user_ip}','${params.user_device}');`;
        db(addSQL).then((result)=>{
            res.end('add success!');
        }).catch((res)=>{
            console.log('报错啦',res)
        })
    }else if(/delete/.test(url.pathname)){//删
        let delSql = `DELETE FROM log WHERE pv_id="${params.pv_id}"`
        db(delSql).then((result)=>{
            res.end('delete success!');
        }).catch((res)=>{
            console.log('报错啦',res)
            res.end(JSON.stringify(result));
        })
    }else if(/update/.test(url.pathname)){//删
        let update = 'UPDATE log SET user_ip="我是修改后的数据ip" WHERE user_device="huawei p31";';
        db(update).then((result)=>{
            res.end(JSON.stringify(result));
        }).catch((res)=>{
            console.log('报错啦',res)
            res.end(JSON.stringify(result));
        })
    }else if(/list/.test(url.pathname)){//查
        let selectSQL = 'select * from log';
        db(selectSQL).then((result)=>{
            res.writeHead(200, {"Content-Type": "application/json;charset=UTF-8"});
            res.end(JSON.stringify(result));
        }).catch((res)=>{
            console.log('报错啦',res)
            res.end(JSON.stringify(result));
        })
    }else{
        res.writeHead(404, {"Content-Type": "text/plain;charset=UTF-8"});
        res.end('404,没有此接口');
    }
} 

module.exports = getApi//注意啊原生nodejs支持支 module.exports 不支持export default等ES6写法